package com.my.sl.emfreosurce.main;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import com.my.sl.emfresource.webpage.MyWeb;
import com.my.sl.emfresource.webpage.Webpage;
import com.my.sl.emfresource.webpage.WebpageFactory;
import com.my.sl.emfresource.webpage.WebpagePackage;


public class SavingEmfModel {

   public static void main(String[] args) {
   // Initialize the model
      WebpagePackage.eINSTANCE.eClass();
      // Retrieve the default factory singleton
      WebpageFactory factory = WebpageFactory.eINSTANCE;

      // Create the content of the model via this program
      MyWeb myWeb = factory.createMyWeb();
      Webpage page = factory.createWebpage();
      myWeb.setDescription("Main webpage");
      myWeb.setTitle("Eclipse EMF");
      page.setName("index");
      page.setKeywords("Eclipse, EMF");
      myWeb.getPages().add(page);

      // As of here we preparing to save the model content

      // Register the XMI resource factory for the .website extension

      Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
      Map<String, Object> m = reg.getExtensionToFactoryMap();
      m.put("myweb", new XMIResourceFactoryImpl());

      // Obtain a new resource set
      ResourceSet resSet = new ResourceSetImpl();

      // Create a resource
      Resource resource = resSet.createResource(URI
          .createURI("website/My.myweb"));
      // Get the first model element and cast it to the right type, in my
      // example everything is hierarchical included in this first node
      resource.getContents().add(myWeb);

      // Now save the content.
      try {
        resource.save(Collections.EMPTY_MAP);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
}
